<template>
  <el-row :gutter="20">
    <el-col :span="18">
      <el-card
        v-loading="loading1"
        element-loading-text="Loading..."
        element-loading-background="#fff"
        style="text-align: left;"
      >
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/community' }"
            >社区</el-breadcrumb-item
          >
          <el-breadcrumb-item>帖子详情</el-breadcrumb-item>
        </el-breadcrumb>
        <h1 v-html="postDetail.title"></h1>
        <div class="user-message">
          <el-avatar
            @click.native="toUserArea(postDetail.userId, postDetail.userName)"
            size="medium"
            :src="postDetail.userName === proxy.$storage.getItem('userInfo').userName ? 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' : 'https://source.unsplash.com/random'"
          ></el-avatar>
          <span @click="toUserArea(postDetail.userId, postDetail.userName)">{{
            postDetail.userName
          }}</span>
          <span>{{ postDetail.createTime }}</span>
          <span
            @click="isFollowedUser"
            v-if="postDetail.userId !== followState.userId"
          >
            <el-icon :class="followState.isFollowed ? 'follow' : ''">
              <Star />
            </el-icon>
            <i>{{ followState.isFollowed ? '已关注' : '关注' }}</i>
          </span>
        </div>
        <el-tag v-for="(item, index) in postDetail.tags" :key="index">{{
          item
        }}</el-tag>
        <Editor
          style="min-height: 50px"
          v-model="postDetail.content"
          :defaultConfig="editorConfig"
          @onCreated="onCreated"
          mode="default"
        />
        <div class="icons">
          <span class="icon-item" @click="toComment">
            <el-icon :size="16">
              <ChatDotSquare />
            </el-icon>
            <span>{{
              postDetail.commentCount ? postDetail.commentCount : '评论'
            }}</span>
          </span>
          <span class="icon-item" @click="isLiked">
            <i
              class="iconfont icon-icon"
              :class="postIsLiked ? 'isLiked' : ''"
            ></i>
            <span>{{ postLikeCount ? postLikeCount : '点赞' }}</span>
          </span>
        </div>
      </el-card>
      <el-card
        v-loading="loading1"
        element-loading-text="Loading..."
        element-loading-background="#fff"
        class="comment-box"
        id="comment-box-info"
      >
        <span class="title">评论</span>
        <el-input
          placeholder="请发表您的评论"
          v-model="commentText"
          ref="focusInput"
          class="input-with-select"
          @keyup-enter="postComment"
        >
          <template #append>
            <el-button
              :class="commentText ? 'isComment' : ''"
              slot="append"
              @click="postComment"
              :disabled="commentText === ''"
              >发表评论</el-button
            >
          </template>
        </el-input>
        <div
          class="comment-main"
          v-for="item in comments"
          :key="item.commentId + '123'"
        >
          <div class="comment-info">
            <div class="info-message">
              <el-avatar
                @click.native="toUserArea(item.userId, item.userName)"
                :size="32"
                shape="square"
                :src="item.url"
                style="margin-top: 2px; float: left"
              ></el-avatar>
              <span>{{ item.userName }}</span>
              <span>{{ item.createTime }}</span>
            </div>
            <!-- <div
              class="info-icon"
              @click="commentReply(item.comment.commentId)"
            >
              <i class="el-icon-chat-line-square"></i>
              <span>{{
                item.comment.commentId === replyCommentId ? '收起' : '回复'
              }}</span>
            </div> -->
          </div>
          <p>{{ item.content }}</p>
          <!-- <div
            class="comment-reply"
            v-show="item.comment.commentId === replyCommentId"
          >
            <el-input
              style="width: 90%"
              placeholder="请发表您的评论"
              v-model="replyComment"
            >
            </el-input>
            <el-button type="primary" :disabled="replyComment ? false : true"
              >回复</el-button
            >
          </div> -->
        </div>
        <div class="button-box" v-show="showMore">
          <el-button v-show="!loading2" type="primary" @click="getPostComments">
            查看更多评论
            <el-icon style="margin-left:5px">
              <ArrowRight />
            </el-icon>
          </el-button>
          <el-button v-show="loading2" type="primary" :loading="loading2">
            加载中
          </el-button>
        </div>
        <div class="noMore" v-show="!showMore">没有更多了....</div>
      </el-card>
    </el-col>
    <el-col :span="6" :class="scroll ? '' : 'scroll'">
      <div class="fixed" @mouseenter="enterScroll" @mouseleave="leaveScroll">
        <el-card class="chicken-box">
          <span>心灵文案</span>
          <p>{{ chicken }}</p>
        </el-card>
        <el-button class="button-box" :icon="Edit" @click="toCreation"
          >发帖</el-button
        >
        <!-- <el-card class="community-box">
          <div class="community-header">
            <img
              src="https://img0.baidu.com/it/u=1697148622,3160789974&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=938"
              alt=""
            />
            <span>高校算法学习社区</span>
          </div>
          <div class="community-message">
            <div class="community-member">
              <p><i class="el-icon-user-solid"></i>社区成员</p>
              <p>134</p>
            </div>
            <div class="community-content">
              <p><i class="el-icon-user-solid"></i>社区内容</p>
              <p>134</p>
            </div>
          </div>
          <div class="community-text">
            <span
              >用于软件工程专业的课程教学，讲义、视频、资料、问题讨论
              鞠小林老师、蒋峥峥老师，欢迎您的到来！</span
            >
          </div>
          <div class="community-manage">
            <div class="manage">
              <span>社区管理员</span>
              <el-avatar
                :size="20"
                src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
              ></el-avatar>
            </div>
            <el-button type="primary" round>加入社区</el-button>
          </div>
        </el-card> -->
        <el-card class="ranking-box">
          <span>学习排行榜</span>
          <el-table :data="rankMessage" style="width: 100%" max-height="400px">
            <el-table-column prop="name" label="用户名" align="center">
            </el-table-column>
            <el-table-column prop="clockNum" label="打卡次数" align="center">
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { useStore } from 'vuex';
import { Editor } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { Base64 } from 'js-base64';
import { ref, reactive, computed, onMounted, onBeforeUnmount, getCurrentInstance, ComponentInternalInstance } from 'vue'
import { ElMessage } from 'element-plus';
import { Star, ChatDotSquare, ArrowRight, Edit } from '@element-plus/icons-vue'


const storeData = useStore();
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 富文本编辑器实例
const editor = ref(null) as any;
// 富文本编辑器配置
const editorConfig = reactive({
  readOnly: true,
});
// 帖子详情信息
interface PostDetail {
  commentCount: Number
  comments: Object
  content: String
  createTime: String
  modules: []
  postId: Number
  status: Number
  tags: []
  title: String
  type: Number
  userId: Number
  userName: String
}
let postDetail = reactive<PostDetail>({
  commentCount: 0,
  comments: {},
  content: '',
  createTime: '',
  modules: [],
  postId: 0,
  status: 0,
  tags: [],
  title: '',
  type: 0,
  userId: 0,
  userName: ''
});
// 评论数据
interface Comments {
  commentId: Number
  content: String
  createTime: String
  entityId: Number
  entityType: Number
  status: Number
  targetId: Number
  userId: Number
  userName: String
  url: String
}
const comments = ref<Comments[]>([]);
// 关注详情
const followState = reactive({
  followAction: 1,
  followUserId: null,
  isFollowed: 0,
  userId: proxy.$storage.getItem('userInfo').userId,
});
// 评论页数
const pageNum = ref(1);
// 发表帖子评论
const commentText = ref('');
// input框的ref
const focusInput = ref();
// 回复评论
// const replyComment = ref('');
// 对应的回复输入框
// const replyCommentId = ref(0);
// 获取当前帖子点赞数以及判断是否已点赞
const postIsLiked = ref(false);
const postLikeCount = ref(0);
// 是否正在加载
const loading1 = ref(false);
const loading2 = ref(false);
// 展示更多
const showMore = ref(false);
// 右侧列表是否滚动
const scroll = ref(false);
// 是否修改昵称
// const showChangeInput = ref(false);
// 鸡汤
const chicken = ref('');

const rankMessage = computed(() => {
  return storeData.state.userSign.rankMessage;
});

onMounted(() => {
  let data = proxy.$route.query;
  const postId = Base64.decode(data.p);
  getPostDetail(Number(postId));
  getChicken();
})

// 获取帖子详情
function getPostDetail(postId: any) {
  loading1.value = true;
  proxy.$request.discussPost
    .detail({ postId: postId, pageNum: pageNum.value })
    .then((res: any) => {
      followState.followUserId = res.data.userId;
      postDetail = res.data;
      if (res.data.comments.list.length !== 0) {
        comments.value.push(...res.data.comments.list);
        comments.value.forEach((item, index) => {
          if (item.userName === proxy.$storage.getItem('userInfo').userName) {
            item.url = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
          } else {
            item.url = `https://source.unsplash.com/random/${index}`;
          }
        })
        showMore.value = true;
      }
      followUser();
      getPostIsLiked();
      loading1.value = false;
    });
};
// 获取评论详情
function getPostComments() {
  loading2.value = true;
  pageNum.value += 1;
  proxy.$request.discussPost
    .detail({ postId: postDetail.postId, pageNum: pageNum.value })
    .then((res: any) => {
      if (res.data.comments.list.length < 5) {
        loading2.value = false;
        showMore.value = false;
      }
      comments.value = [];
      comments.value.push(...res.data.comments.list);
      comments.value.forEach((item, index) => {
        if (item.userName === proxy.$storage.getItem('userInfo').userName) {
          item.url = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
        } else {
          item.url = `https://source.unsplash.com/random/${index}`;
        }
      })
      loading2.value = false;
    });
};
// 跳转到用户专区
function toUserArea(userId: any, userName: any) {
  // 用户id加密
  const i = Base64.encodeURI(userId);
  // 用户名加密
  const n = Base64.encodeURI(userName);
  proxy.$router.push({
    path: '/contentManage',
    query: { i, n },
  });
};
// 获取鸡汤
function getChicken() {
  proxy.$request.chicken.getChicken().then((res: any) => {
    chicken.value = res.data;
  });
};
// 判断是否是已经关注用户
function followUser() {
  proxy.$request.follow
    .myfollows({
      userId: proxy.$storage.getItem('userInfo').userId,
      pageNum: 1,
      pageSize: 100,
    })
    .then((res: any) => {
      if (!res.data) {
        return;
      }
      const id = [] as any;
      res.data.list.forEach((item: any) => {
        id.push(item.userId);
      });
      if (id.indexOf(followState.followUserId) !== -1) {
        followState.isFollowed = 1;
        followState.followAction = 0;
      }
    });
};
// 是否关注用户
function isFollowedUser() {
  proxy.$request.follow.state(followState).then(() => {
    followState.isFollowed = !followState.isFollowed ? 1 : 0;
    followState.followAction = !followState.followAction ? 1 : 0;
    proxy.$emit('getFollows');
  });
};
// 创建富文本编辑器实例对象
function onCreated(Editor: any) {
  editor.value = Object.seal(Editor); // 一定要用 Object.seal() ，否则会报错
};
// 去评论
function toComment() {
  focusInput.value.focus();
};
// 获取当前页面帖子点赞数以及判断是否已点赞
function getPostIsLiked() {
  let postIds = [];
  postIds.push(postDetail.postId);
  proxy.$request.like
    .count({
      postIds: postIds,
      userId: proxy.$storage.getItem('userInfo').userId,
    })
    .then((res: any) => {
      postIsLiked.value = res.data[0].isLiked;
      postLikeCount.value = res.data[0].likeCount;
    });
};
// 点赞/取消点赞
function isLiked() {
  let action = postIsLiked.value ? 0 : 1;
  proxy.$request.like
    .action({
      action: action,
      isLiked: postIsLiked.value,
      postId: postDetail.postId,
      userId: proxy.$storage.getItem('userInfo').userId,
    })
    .then(() => {
      getPostIsLiked();
    });
};
// 评论帖子
function postComment() {
  if (!commentText.value) return;
  proxy.$request.comment
    .newComment({
      content: commentText.value,
      entityId: postDetail.postId,
      entityType: 1,
      targetId: postDetail.userId,
      userId: proxy.$storage.getItem('userInfo').userId,
    })
    .then(() => {
      commentText.value = '';
      proxy.$request.discussPost
        .detail({ postId: postDetail.postId, pageNum: 1 })
        .then((res: any) => {
          if (res.data.comments.list.length < 5) {
            loading2.value = false;
            showMore.value = false;
          }
          comments.value = [];
          comments.value.push(...res.data.comments.list);
          ElMessage({
            message: '评论成功',
            type: 'success',
            duration: 1000,
          });
        });
    });
};
// // 点击回复图标显示回复输入框
// commentReply(commentId) {
//   console.log(this.replyCommentId, commentId);
//   if (this.replyCommentId === 0) {
//     this.replyCommentId = commentId;
//   } else if (this.replyCommentId === commentId) {
//     this.replyCommentId = 0;
//   } else if (this.replyCommentId !== commentId) {
//     this.replyCommentId = commentId;
//   }
// },
// // 回复用户评论
// replyUserComment(commentId, userId) {
//   if (!this.replyComment) return;
//   this.$request.comment
//     .newComment({
//       content: this.replyComment,
//       entityId: commentId,
//       entityType: 2,
//       targetId: userId,
//       userId: this.$storage.getItem('userInfo').userId,
//     })
//     .then(() => {
//       this.commentText = '';
//       this.getPostDetail(this.postDetail.postId);
//       this.$message({
//         message: '评论成功',
//         type: 'success',
//         duration: 1000,
//       });
//     });
// },
// 当进入右侧
function enterScroll() {
  scroll.value = true;
};
function leaveScroll() {
  scroll.value = false;
};
// 点击跳转到我要创作
function toCreation() {
  proxy.$router.push('/creation');
};

onBeforeUnmount(() => {
  const Editor = editor.value;
  if (Editor === null) return;
  Editor.destroy(); // 组件销毁时，及时销毁编辑器
});
</script>

<style lang="less" scoped>
h1 {
  text-align: left;
  margin: 15px 0;
  font-size: 26px;
  font-weight: 700;

}

.user-message {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  margin-bottom: 10px;
  text-align: left;

  .el-avatar {
    float: left;
    margin: 2px;
  }

  span:nth-child(2) {
    margin: 0 10px;
    color: #555666;
    font-size: 20px;

    &:hover {
      cursor: default;
      color: #303133;
    }
  }

  span:nth-child(3) {
    color: #777888;
  }

  span:nth-child(4) {
    color: #777888;
    user-select: none;
    float: right;
    width: 100px;
    margin-right: 20px;
    font-size: 16px;

    &:hover {
      color: #555666;
      cursor: pointer;
    }

    .el-icon {
      float: left;
      margin: 13px 0 0 0;
    }

    .follow {
      color: #409eff;
    }

    i:nth-child(2) {
      float: left;
      margin-left: 5px;
    }
  }
}

.el-tag {
  margin: 10px 15px 10px 0;
}

.icons {
  height: 40px;
  line-height: 40px;

  .icon-item {
    font-size: 14px;
    color: #999999;
    margin-right: 30px;
    cursor: pointer;
    user-select: none;

    .el-icon {
      float: left;
      margin: 14px 0 0 0;
    }

    span {
      margin-left: 5px;
    }

    &:hover {
      color: #555666;
    }
  }

  .isLiked {
    color: #409eff;
  }
}

.comment-box {
  margin-top: 20px;
  text-align: left;

  .title {
    display: block;
    color: #20232c;
    font-size: 16px;
    font-weight: 700;
    margin-bottom: 15px;
  }

  .input-with-select {
    margin-bottom: 20px;
  }

  .isComment {
    background-color: #409eff;
    color: #fff;

    &:hover {
      background-color: #66b1ff;
      color: #fff;
    }
  }

  .comment-main {
    border-top: 1px solid #eee;

    .comment-info {
      height: 18px;
      margin-top: 10px;
      color: #777888;
      font-size: 14px;
      text-align: left;

      .info-message {
        span:nth-child(2) {
          font-size: 20px;
          color: #73767a;
          margin-left: 5px;
        }

        span:nth-child(3) {
          margin-left: 10px;
          font-size: 12px;
        }
      }

      .info-icon {
        float: right;
        display: none;

        span {
          margin: 0 5px;
        }
      }
    }

    &:hover {
      .info-icon {
        display: inline-block;
        cursor: pointer;
      }
    }

    p {
      font-size: 16px;
      margin-top: 15px;
      line-height: 22px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      margin-left: 36px;
      color: #000000;
    }

    // .comment-reply {
    //   /deep/ .el-input__inner {
    //     float: left;
    //     border-radius: 20px;
    //   }
    //   .el-button {
    //     float: right;
    //   }
    // }
  }

  .button-box {
    height: 40px;
    line-height: 40px;
    width: 100%;

    .el-button--primary {
      display: block;
      margin: 0 auto;
    }
  }

  .noMore {
    color: #909399;
    font-size: 14px;
    text-align: center;
  }
}

.fixed {
  height: 566px;
  position: fixed;
  right: 30px;
  width: 286px;
  overflow: auto;

  .chicken-box {
    span {
      display: block;
      margin-bottom: 10px;
      font-weight: 600;
    }

    p {
      font-family: '宋体';
      padding: 0 10px;
      font-size: 16px;
      color: #e6a23c;
      overflow-wrap: break-word;
      display: -webkit-box;
      -webkit-line-clamp: 6;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }

  .button-box {
    margin: 10px 0;
    width: 286px;
    height: 60px;
    font-size: 20px;
  }

  // .community-box {
  //   min-height: 100px;
  //   .community-header {
  //     height: 40px;
  //     line-height: 40px;
  //     margin-bottom: 15px;
  //     img {
  //       float: left;
  //       height: 40px;
  //       width: 40px;
  //       margin-right: 10px;
  //       border-radius: 3px;
  //     }
  //     span {
  //       font-size: 14px;
  //       font-weight: 700;
  //     }
  //   }

  //   .community-message {
  //     border-top: 1px solid #eee;
  //     border-bottom: 1px solid #eee;

  //     .community-member,
  //     .community-content {
  //       width: 50%;
  //       display: inline-block;
  //       text-align: center;
  //       p:nth-child(1) {
  //         color: #999aaa;
  //         font-size: 16px;
  //         i {
  //           margin-right: 5px;
  //         }
  //       }
  //     }

  //     .community-member {
  //       box-sizing: border-box;
  //       border-right: 1px solid #eee;
  //     }
  //   }

  //   .community-text {
  //     padding: 10px 0;
  //     border-bottom: 1px solid #eee;

  //     span {
  //       color: #777888;
  //       font-size: 14px;
  //     }
  //   }
  //   .community-manage {
  //     padding: 10px 0;
  //     .manage {
  //       height: 26px;
  //       line-height: 26px;
  //       span {
  //         font-size: 14px;
  //         color: #222226;
  //       }
  //       .el-avatar {
  //         float: right;
  //         margin: 3px;
  //       }
  //     }

  //     .el-button {
  //       width: 100%;
  //       margin-top: 15px;
  //     }
  //   }
  // }

  .ranking-box {
    span {
      display: block;
      margin-bottom: 10px;
      font-weight: 600;
    }
  }
}

.scroll {
  ::-webkit-scrollbar {
    display: none !important;
  }
}
</style>
